const { MessageMedia } = require('whatsapp-web.js');
const config = require('../config');
const path = require('path');
const filterService = require('./filterService');  // 导入过滤服务
const logger = require('../utils/logger');  // 导入日志工具

/**
 * 处理传入的消息
 * @param {Object} message WhatsApp消息对象
 * @returns {Object} 处理后的消息对象
 */
const processIncomingMessage = (message) => {
  try {
    // 添加日志，查看输入的消息对象结构
    console.log('处理消息对象:', JSON.stringify(message, (key, value) => 
      key === 'data' && typeof value === 'string' && value.length > 100 
        ? value.substring(0, 100) + '...' 
        : value
    ));
    
    // 检查消息对象是否已经是处理过的格式
    if (message && typeof message === 'object' && message.body !== undefined && !message.getChat) {
      console.log('消息已经是处理过的格式，简单包装后返回');
      // 这可能是已经处理过的消息对象，简单包装后返回
      return {
        id: message.id || `temp_${Date.now()}`,
        timestamp: message.timestamp || new Date().toISOString(),
        from: message.from || { id: 'unknown', name: '未知' },
        body: message.body || '内容不可用',
        hasMedia: message.hasMedia || false,
        type: message.type || 'text',
        hasSensitiveContent: message.hasSensitiveContent || false,
        originalContent: message.body || message.originalContent || '内容不可用'
      };
    }
    
    // 如果是简单字符串，直接返回包装的消息
    if (typeof message === 'string') {
      console.log('处理纯文本消息');
      return {
        id: `temp_${Date.now()}`,
        timestamp: new Date().toISOString(),
        from: { id: 'unknown', name: '未知' },
        body: message,
        hasMedia: false,
        type: 'text',
        hasSensitiveContent: false,
        originalContent: message
      };
    }
    
    // 检查消息对象的一致性
    if (!message || typeof message !== 'object') {
      console.warn('收到无效的消息对象类型:', typeof message);
      return {
        id: `unknown_${Date.now()}`,
        timestamp: new Date().toISOString(),
        from: { id: 'system', name: '系统' },
        body: '无效消息',
        hasMedia: false,
        type: 'text',
        hasSensitiveContent: false,
        originalContent: '无效消息'
      };
    }
    
    // 如果没有ID对象，尝试从其他字段提取ID
    let messageId = 'unknown';
    if (message.id) {
      messageId = typeof message.id === 'object' ? (message.id._serialized || message.id.id || 'unknown') : message.id;
    } else if (message._data && message._data.id) {
      messageId = message._data.id;
    }
    
    // 从消息对象中提取可能的文本内容
    let messageBody = '内容不可用';
    if (message.body !== undefined) {
      messageBody = message.body;
    } else if (message.text !== undefined) {
      messageBody = message.text;
    } else if (message.content !== undefined) {
      messageBody = message.content;
    } else if (message.message !== undefined) {
      messageBody = message.message;
    } else if (message._data && message._data.body) {
      messageBody = message._data.body;
    }
    
    // 提取发送者信息
    let fromInfo = { id: 'unknown', name: '未知' };
    if (message.from) {
      if (typeof message.from === 'object') {
        fromInfo = {
          id: message.from.id || message.from.user || 'unknown',
          name: message.from.name || message.from.pushname || '未知'
        };
      } else {
        fromInfo = { id: message.from, name: '未知' };
      }
    } else if (message._data && message._data.from) {
      fromInfo = { id: message._data.from, name: '未知' };
    }
    
    // 处理时间戳
    let timestamp = message.timestamp || new Date().toISOString();
    if (typeof timestamp === 'number') {
      timestamp = new Date(timestamp * 1000).toISOString();
    }
    
    // 构建基本消息对象
    const processedMessage = {
      id: messageId,
      timestamp: timestamp,
      from: fromInfo,
      body: messageBody,
      hasMedia: message.hasMedia || false,
      type: message.type || 'text',
      hasSensitiveContent: false,
      originalContent: messageBody, // 保存原始内容
      // 添加其他可能有用的属性
      fromMe: message.fromMe || false
    };
    
    // 使用filterService检查是否包含敏感内容
    if (messageBody) {
      const filterResult = filterService.filterSensitiveContent(messageBody);
      if (filterResult.hasSensitiveContent) {
        processedMessage.hasSensitiveContent = true;
        processedMessage.body = filterResult.filteredText;
        processedMessage.sensitiveType = filterResult.type;
        logger.info('检测到敏感内容', { 
          messageId: messageId, 
          type: filterResult.type,
          matches: filterResult.matches
        });
      }
    }
    
    // 如果能获取媒体信息，同步处理
    if (message.hasMedia && message.mediaData) {
      processedMessage.type = message.mediaData.type || 'unknown';
      processedMessage.media = {
        data: message.mediaData.data,
        mimetype: message.mediaData.mimetype,
        filename: message.mediaData.filename
      };
    }
    
    return processedMessage;
  } catch (error) {
    logger.error('处理消息时出错:', error);
    return {
      id: `error_${Date.now()}`,
      timestamp: new Date().toISOString(),
      from: { id: 'system', name: '系统错误' },
      body: '消息处理失败',
      hasMedia: false,
      type: 'text',
      hasSensitiveContent: false,
      originalContent: '消息处理失败'
    };
  }
};

/**
 * 检查文本是否包含敏感数字
 * @param {string} text 待检查的文本
 * @returns {boolean} 是否包含敏感数字
 */
const containsSensitiveNumbers = (text) => {
  const result = filterService.detectSensitiveContent(text);
  return result.hasSensitiveContent;
};

/**
 * 掩码电话号码
 * @param {string} phoneNumber 完整电话号码
 * @returns {string} 掩码后的电话号码
 */
const maskPhoneNumber = (phoneNumber) => {
  return filterService.maskPhoneNumber(phoneNumber);
};

/**
 * 根据用户角色处理消息显示
 * @param {Object} message 消息对象
 * @param {string} role 用户角色
 * @returns {Object} 处理后的消息对象
 */
const processMessageForRole = (message, role) => {
  // 深拷贝消息对象
  const processedMessage = JSON.parse(JSON.stringify(message));
  
  // 管理员可以看到所有信息
  if (role === config.roles.ADMIN) {
    // 如果有敏感内容，还原原始内容
    if (processedMessage.hasSensitiveContent) {
      processedMessage.body = processedMessage.originalContent;
    }
    // 还原原始电话号码
    if (processedMessage.from && processedMessage.from.originalPhone) {
      processedMessage.from.phone = processedMessage.from.originalPhone;
    }
    return processedMessage;
  }
  
  // 销售人员看不到敏感内容和原始电话号码
  delete processedMessage.originalContent;
  if (processedMessage.from) {
    delete processedMessage.from.originalPhone;
  }
  
  return processedMessage;
};

/**
 * 发送消息
 * @param {string} to 接收者ID
 * @param {string} content 消息内容
 * @param {Object} user 发送者用户信息
 * @returns {Object} 发送结果
 */
const sendMessage = async (to, content, user) => {
  try {
    // 这里调用WhatsApp服务发送消息
    const whatsappService = require('./whatsappService');
    const response = await whatsappService.sendMessage(to, content);
    
    // 记录消息
    // 这里可以将消息保存到数据库
    
    return {
      success: true,
      messageId: response.id.id,
      timestamp: response.timestamp
    };
  } catch (error) {
    console.error('发送消息时出错:', error);
    throw error;
  }
};

/**
 * 发送预设文件
 * @param {string} to 接收者ID
 * @param {string} presetId 预设文件ID
 * @param {Object} user 发送者用户信息
 * @returns {Object} 发送结果
 */
const sendPresetFile = async (to, presetId, user) => {
  try {
    // 查找预设文件信息
    // 这里应该从数据库中获取预设文件信息
    const presetFile = { /* 从数据库中获取 */ };
    
    if (!presetFile) {
      throw new Error('预设文件不存在');
    }
    
    // 构建文件路径
    const filePath = path.resolve(presetFile.filePath);
    
    // 发送文件
    const whatsappService = require('./whatsappService');
    const response = await whatsappService.sendFile(to, filePath, presetFile.description);
    
    return {
      success: true,
      messageId: response.id.id,
      timestamp: response.timestamp,
      fileName: presetFile.name
    };
  } catch (error) {
    console.error('发送预设文件时出错:', error);
    throw error;
  }
};

/**
 * 获取聊天历史记录
 * @param {string} chatId 聊天ID
 * @param {number} limit 消息数量限制
 * @param {string} role 用户角色
 * @returns {Array} 消息列表
 */
const getChatHistory = async (chatId, limit = 50, role) => {
  try {
    const whatsappService = require('./whatsappService');
    const messages = await whatsappService.getChatHistory(chatId, limit);
    
    // 根据用户角色处理消息
    const processedMessages = messages.map(msg => {
      const processedMsg = processIncomingMessage(msg);
      return processMessageForRole(processedMsg, role);
    });
    
    return processedMessages;
  } catch (error) {
    console.error('获取聊天历史时出错:', error);
    throw error;
  }
};

module.exports = {
  processIncomingMessage,
  processMessageForRole,
  sendMessage,
  sendPresetFile,
  getChatHistory,
  containsSensitiveNumbers,
  maskPhoneNumber
}; 